package com.buaa.aimall.Utils.Client;

import com.buaa.aimall.Utils.Config.BUAAComputeConfig;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class BUAAComputeClient {

    private final BUAAComputeConfig config;

    @Autowired
    public BUAAComputeClient(BUAAComputeConfig config) {
        this.config = config;
    }

    public ResponseEntity<String> resourceDeployment(int vgpuNum, int cpuNum, int memory, String endTime) {
        String url = UriComponentsBuilder.fromHttpUrl(config.getBaseUrl())
                .path("/resource-repo/request/deployment")
                .build()
                .toUriString();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("spaceId", config.getSpaceId());
        requestBody.put("userId", config.getUserId());
        requestBody.put("imageId", config.getImageId());
        requestBody.put("resName", UUID.randomUUID().toString().substring(24));
        requestBody.put("vgpuNum", vgpuNum);
        requestBody.put("cpuNum", cpuNum);
        requestBody.put("memory", memory);
        requestBody.put("type", "CPU_GPU");
        requestBody.put("endTime", endTime);
        requestBody.put("gpuId", config.getGpuId());
        requestBody.put("cpuId", config.getCpuId());

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(url, requestEntity, String.class);
    }
}
